import { app, shell, BrowserWindow, ipcMain, Menu,Tray,dialog  } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/logo.png?asset'
import {createDataTable} from './dbSql/sqlite3db'


let  mainWindow = null;
let childWindow = null; // 用于存储子窗口的引用
let shezhiChildWindow = null; // 用于存储子窗口的引用
const url = process.env.ELECTRON_RENDERER_URL
let width = 900;
let height = 680;
const winURL = process.env.NODE_ENV === 'development'
  ? process.env.ELECTRON_RENDERER_URL
  : `file://${__dirname}/index.html`

function createWindow(): void {
  let isWin = false
   if(process.platform === "darwin"){
     isWin = true
   }
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: width,
    height: height,
    show: false,
    autoHideMenuBar: true,
    frame:isWin,
    minHeight:550,
    minWidth:400,
   titleBarStyle:"hidden",
   icon:join(__dirname, '../logo.png'),
    // transparent:true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: false,
      nodeIntegration:true,
      webSecurity: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  let tray ;
  tray = new Tray(join(__dirname, '../logo.png'))
  tray.setToolTip('秋秋聊天系统')
  const contextMenu = Menu.buildFromTemplate([
    { label: '显示窗口', click:()=>{
        mainWindow.show()
      }},
    { label: '退出系统', click:()=>{
        app.quit()
      } },

  ])
  // 打开DevTools

  tray.setContextMenu(contextMenu)
  tray.on('double-click', () => {
    // 双击通知区图标实现应用的显示或隐藏
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    mainWindow.isVisible() ? mainWindow.setSkipTaskbar(false) : mainWindow.setSkipTaskbar(true);
  });
  //最小化窗口
  ipcMain.on('window-min',()=>{
    mainWindow.minimize();
  })
  ipcMain.on('window-max',()=>{
    if(mainWindow.isMaximized()){
      mainWindow.restore();
    }else{
      mainWindow.maximize();
    }
  })
  //关闭窗口
  ipcMain.on('win-closed',()=>{
    if (process.platform !== 'darwin') {
      // app.quit()
      mainWindow.hide()
    }
  })
  ipcMain.on('isWin',(event)=>{
    event.reply('msg',isWin);
  })
  ipcMain.on("open-window",(event,path)=>{
    createChildWindow(path,'历史信息');
  })
  ipcMain.on("shezhi-window",(event,path)=>{
    console.log(path)
    shezhiWindow(path,'系统设置');
  })

  ipcMain.on("groupChatWindow",(event, args)=>{

    if(args.isShow){
      mainWindow.setSize(args.width, args.height);
    }else{
      mainWindow.setSize(args.width, args.height);
    }

  })
  ipcMain.on("open-user-box",(event,path)=>{
    createChildWindow(path,'好友管理器');
    childWindow.setSize(800, 700);
  })

  ipcMain.on("open-sousuo",(event,path)=>{
    createChildWindow(path,'好友/群搜索');
    childWindow.setSize(800, 700);
  })
  ipcMain.on("open-size",(event,path)=>{
    mainWindow.setSize(path.width,path.height);
    mainWindow.setResizable(path.resizable);
    mainWindow.setMenuBarVisibility(false);
  })

}





// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  createWindow()
  createDataTable();
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
 function createChildWindow(url,text){
   if(childWindow){
     childWindow.focus();
     return
   }
   childWindow = new BrowserWindow({
     width: 600,
     height: 750,
     frame:true,
     autoHideMenuBar: false,
     modal: false, // 将窗口设置为模态窗口（仅在 macOS 上有效）
     show: false ,// 初始时不显示窗口，稍后可以调用 show() 方法显示
     parent:mainWindow
   });
   if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
     childWindow.loadURL(process.env['ELECTRON_RENDERER_URL']+"#"+url)
   } else {
     childWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: url })
   }
    // 加载子窗口的 HTML 文件

   // 当窗口关闭时，释放资源
   childWindow.on('closed', () => {
     childWindow = null;
   });
   childWindow.setTitle(text)
   childWindow.show();
 }

function shezhiWindow(url,text){
  if(shezhiChildWindow){
    shezhiChildWindow.focus();
    return
  }
  shezhiChildWindow = new BrowserWindow({
    width: 850,
    height: 750,
    frame:true,
    autoHideMenuBar: false,
    parent:mainWindow,
    transparent:true,
    titleBarStyle:"hidden",
    modal: false, // 将窗口设置为模态窗口（仅在 macOS 上有效）
    show: false ,// 初始时不显示窗口，稍后可以调用 show() 方法显示
  });
  // 加载子窗口的 HTML 文件
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    shezhiChildWindow.loadURL(process.env['ELECTRON_RENDERER_URL']+"#"+url)
  } else {
    shezhiChildWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: url })
  }
  // 当窗口关闭时，释放资源
  shezhiChildWindow.on('closed', () => {
    shezhiChildWindow = null;
  });
  shezhiChildWindow.show();
}
